package 多线程09_原子访问;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: TestThreadAtom
 * @Author: AllenSun
 * @Date: 2022/3/18 下午11:51
 */
public class TestThreadAtom {

    private static int value=0;
    private static AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) {
        int number = 100000;
        Thread[] threads1 = new Thread[number];
        for (int i=0;i<number;i++) {
            Thread t = new Thread() {
                public void run() {
                    value++;
                }
            };
            t.start();
            threads1[i] = t;
        }

        //等待这些线程全部结束
        for (Thread t:threads1) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.printf("%d个线程进行value++后，value的值变成:%d%n", number,value);

        Thread[] ts2 = new Thread[number];
        for (int i = 0; i < number; i++) {
            Thread t =new Thread(){
                public void run(){
                    atomicInteger.incrementAndGet();
                }
            };
            t.start();
            ts2[i] = t;
        }

        //等待这些线程全部结束
        for (Thread t : ts2) {
            try {
                t.join();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.printf("%d个线程进行atomicValue.incrementAndGet();后，atomicValue的值变成:%d%n", number,atomicInteger.intValue());

    }
}
